package net.srcz.jsjvm.client;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashSet;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import net.srcz.jsjvm.core.Converter;

public class Main {

	public Main() throws Exception {
		//File folder = new File("./bin");
		FileOutputStream fos = new FileOutputStream("output.js");
		/*
		String className = "test";
		File[] classPath = new File[] {new File("."),
				new File("C:\\Users\\a015843\\Documents\\perso\\groovy-1.7.0\\lib\\groovy-1.7.0.jar"),
				new File("C:\\jdev10132\\jdk\\jre\\lib\\rt.jar")};
		*/
		String className = "net.srcz.jsjvm.demo.Essai";
		File[] classPath = new File[] {new File("./target/classes/"),
				new File("C:\\jdev10132\\jdk\\jre\\lib\\rt.jar")};
		lazyConvert(classPath,className,fos);
		fos.close();
	}
	
	public static void lazyConvert(File[] classpath, String className, OutputStream os) throws IOException {
		Set<String> loaded = new HashSet();
		HashSet<String> needToConvert = new HashSet();
		needToConvert.add(className.replaceAll("\\.","/"));
		while(!needToConvert.isEmpty()) {
			String[] names = needToConvert.toArray(new String[0]);
			needToConvert.clear();
			for(String name : names) {
				if(loaded.contains(name))
					continue;
				System.out.println("loading "+name);
				InputStream classInput = getClass(classpath, name);
				needToConvert.addAll(Converter.convert(classInput,os));
				needToConvert.clear();
				classInput.close();
				loaded.add(name);
			}
		}
	}
	
	public static InputStream getClass(File[] classpath, String name) throws IOException {
		String path = name+".class";
		for(File folder : classpath) {
			if(folder.isDirectory()) {
				File f = new File(folder,path);
				if(f.exists()) {
					return new FileInputStream(f);
				}
			} else {
				ZipInputStream zip = new ZipInputStream(new FileInputStream(folder));
				while(true) {
					ZipEntry ze = zip.getNextEntry();
					if(ze == null)
						break;
					if(ze.getName().equals(path)) {
						return zip;
					}
				}
			}
		}
		throw new RuntimeException("Cannot find class "+name+" in classpath");
	}
	
	public static void main(String[] args) {
		try {
			new Main();
			System.out.println("done");
		} catch(Exception ex) {
			ex.printStackTrace();
		}
	}
}
